package com.atguigu.servlet;

import com.atguigu.domain.Book;
import com.atguigu.domain.BookItems;
import com.atguigu.domain.Cart;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;
import org.omg.PortableInterceptor.INACTIVE;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "CartServlet",urlPatterns = "/cart")
public class CartServlet extends BaseServlet {

    private BookService bookService = new BookServiceImpl();
    /** 没有起作用 */
    @Deprecated
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /** 给购物车中添加商品 */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book = WebUtils.map2Bean(req, new Book());
        Book oneBook = bookService.getOneBook(book.getId());
        // 判断 如果查询出来的不是null 也就是当前ID 的图书是存在的
        if (oneBook != null) {
            int bookId = book.getId();
            HttpSession session = req.getSession();
            Cart cart = (Cart)session.getAttribute("cart");
            if (cart == null) {
                cart = new Cart();
                cart.add(bookId,new BookItems(oneBook,1));
                session.setAttribute("cart",cart);
            }else {
                BookItems bookItems = cart.get(bookId);
                if (bookItems == null) {
                    cart.add(bookId,new BookItems(oneBook,1));
                }else {
                    bookItems.setCount(bookItems.getCount() + 1);
                }
            }
            session.setAttribute("addBook",oneBook);
        }
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }

    /** 给购物车中添加商品 */
    protected void addAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book = WebUtils.map2Bean(req, new Book());
        Map<String,Object> map = new HashMap<>();
        Book oneBook = bookService.getOneBook(book.getId());
        // 判断 如果查询出来的不是null 也就是当前ID 的图书是存在的
        if (oneBook != null) {
            int bookId = book.getId();
            HttpSession session = req.getSession();
            Cart cart = (Cart)session.getAttribute("cart");
            if (cart == null) {
                cart = new Cart();
                cart.add(bookId,new BookItems(oneBook,1));
                session.setAttribute("cart",cart);
            }else {
                BookItems bookItems = cart.get(bookId);
                if (bookItems == null) {
                    cart.add(bookId,new BookItems(oneBook,1));
                }else {
                    bookItems.setCount(bookItems.getCount() + 1);
                }
            }
            map.put("totalCount",cart.getTotalCount());
            map.put("bookName",oneBook.getName());
            session.setAttribute("addBook",oneBook);
        }
        Gson gson = new Gson();
        String json = gson.toJson(map);
        resp.getWriter().write(json);
    }

    /** 删除购物车中的某一项 */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = getCart(req);
        cart.delete(Integer.parseInt(req.getParameter("book_id")));
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }
    /** 修改购物车的某一项的数量 */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = getCart(req);
        String num = req.getParameter("count");
        int count = 1;
        try {
            count = Integer.parseInt(num);
            if (count < 1)
                count = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        cart.update(Integer.parseInt(req.getParameter("book_id")),count);
        // 返回上一个url
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }
    /** ajax update cartItem count */
    protected void updateAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = getCart(req);
        String num = req.getParameter("count");
        int count = 1;
        try {
            count = Integer.parseInt(num);
            if (count < 1)
                count = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String book_id = req.getParameter("book_id");
        cart.update(Integer.parseInt(book_id),count);
        // 返回上一个url
        int totalCount = cart.getTotalCount();
        BigDecimal totalAllMoney = cart.getTotalAllMoney();
        BigDecimal itemTotalMoney = cart.get(Integer.parseInt(book_id)).getTotalMoney();
        Map<String,Object> map = new HashMap<>();
        map.put("totalCount",totalCount);
        map.put("totalAllMoney",totalAllMoney);
        map.put("itemTotalMoney",itemTotalMoney);

        Gson gson = new Gson();
        String json = gson.toJson(map);
        resp.getWriter().write(json);
        /*String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);*/
    }
    /** 清空购物车 */
    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = getCart(req);
        cart.clear();
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }
    /**  HttpServletRequest 中获取购物车 */
    private Cart getCart(HttpServletRequest req) {
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        return cart;
    }
}
